import pygame,sys,os
from pygame.locals import *
from config_set import CONFIG

#游戏初始化
def game_init():
    pygame.init()
    pygame.display.set_caption(CONFIG['capation'])
    screen = pygame.display.set_mode(CONFIG['screen_size'])
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill(CONFIG['background_color'])
    return screen,background

#处理退出
def handle_exit(run,events):
    for event in events:
        if event.type == QUIT:
            run = False
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            run = False
    return run
#加载目录
def load_dir():
    main_dir = os.path.split(os.path.abspath(__file__))[0]
    pic_dir = os.path.join(main_dir,'pic')
    font_dir = os.path.join(main_dir,'font')
    sound_dir = os.path.join(main_dir,'sound')
    #更新配置
    CONFIG['main_dir'] = main_dir
    CONFIG['pic_dir'] = pic_dir
    CONFIG['font_dir'] = font_dir
    CONFIG['sound_dir'] = sound_dir
    
#加载图片的通用函数，第一个为图片名字，第二个是否更改图片大小，第三个为是否透明，第四个为图片更改的大小
def load_pic(name,set_size=None,colorkey=None,size=(100,100)):
    fullname = os.path.join(CONFIG['pic_dir'],name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error:
        print('Cannot load image:',fullname)
        raise SystemExit
    if set_size:
        image = pygame.transform.scale(image,size)
    image = image.convert_alpha()
    if colorkey is not None:
        if colorkey == -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey,RLEACCEL)
    return image,image.get_rect()
#加载音效
def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer:
        return NoneSound()
    fullname = os.path.join(CONFIG['sound_dir'],name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error:
        print("Cannot load sound:",fullname)
        raise SystemExit
    return sound 
#加载字体
def load_font(name,font_size):
    fullname = os.path.join(CONFIG['font_dir'],name)
    try:
        font = pygame.font.Font(fullname,font_size)
    except pygame.error:
        print("Cannot load font:",fullname)
        raise SystemExit
    return font
     
#绘制文字的函数,第一个是文本，第二哥是字体，第二个是字体大小，第三个是颜色，第四个是绘制的surface，第五个是x坐标，第六个是y坐标
def draw_text(text,name,font_size,color,surface,x,y):
   font = load_font(name,font_size)
   text_set = font.render(text,1,color)
   surface.blit(text_set,(x,y))
def load_background(state,size=None):
    if size is None:
        size = CONFIG['screen_size']
    name = CONFIG['background_pic'][state]
    background,_ = load_pic(name,set_size=True,size=size)
    return background
    